import 'dart:async';

import 'package:get/get.dart';
import 'package:ty_smart_watch/bean/body_data_bean.dart';
import 'package:ty_smart_watch/bean/sport_recorder_bean.dart';
import 'package:ty_smart_watch/ble/ble_util.dart';
import 'package:ty_smart_watch/common/function_id.dart';
import 'package:ty_smart_watch/common/images_url.dart';
import 'package:ty_smart_watch/utils/Log.dart';
import 'package:ty_smart_watch/utils/data_util.dart';

class WatchDataController extends GetxController {
  var list = <BodyDataBean>[
    BodyDataBean(HEART, GRID_ICON_HEART, "心率", "0", "bmp", 0xFFFFEEF1),
    BodyDataBean(SPORT_RECORDER, GRID_ICON_SPORT, "运动记录", "0", "公里", 0xFFFFF2E4),
    BodyDataBean(BLOOD_OXYGEN, GRID_ICON_BLOOD_OXYGEN, "血氧", "0", "%", 0xFFFFE7E4),
    BodyDataBean(BLOOD_PRESSURE, GRID_ICON_BLOOD_PRESSURE, "血压", "0", "", 0xFFFFE7F1),
  ].obs;

  final _getBleDataList = [
    //心率信息
    BleUtil.makeWriteData(functionId: HEART),
    //血压信息
    BleUtil.makeWriteData(functionId: BLOOD_PRESSURE),
    //获取运动数据
    BleUtil.makeWriteData(functionId: SPORT_RECORDER),
    //血氧信息
    BleUtil.makeWriteData(functionId: BLOOD_OXYGEN),
  ];

  //获取对应的信息
  getBleData(String mac) {
    int index = 0;
    Timer(const Duration(milliseconds: 50), () {
      Log.d("读取独立设备数据");
      Timer.periodic(const Duration(milliseconds: 50), (timer) {
        if (index < _getBleDataList.length) {
          var data = _getBleDataList[index];
          BleUtil.writeBleData(mac, data);
          index++;
        } else {
          Log.d("数据发送完成");
          timer.cancel();
        }
      });
    });
  }

  updateData(int id, String data) {
    // Log.d("更新请求：$id >  $data");
    var item = list.firstWhere((element) => element.id == id);
    item.data = data;
    list.refresh();
  }

  final DateUtil _dateUtil = DateUtil();

  ///更新智能生活页运动记录数据
  updateTodaySportDistance(List<SportBean> sportList) {
    List<SportBean> sportDataList =
        sportList.where((sport) => _dateUtil.isToDay(sport.timeStamp, isMs: true)).toList();
    int mDistance = 0;
    for (var data in sportDataList) {
      if (data.distance != -1) {
        mDistance += data.distance;
      }
    }
    Log.d("今日运动距离总和： $mDistance");
    //更新运动距离总和数据
    var item = list.firstWhere((element) => element.id == SPORT_RECORDER);
    item.data = (mDistance / 1000).toStringAsFixed(2);
  }
}
